package cc.rengu.igas.share.core.service.trans;

import cc.rengu.igas.channel.upac.facade.bean.CustomerInfo;
import cc.rengu.igas.channel.upac.facade.bean.TokenPayInfo;
import cc.rengu.igas.channel.upac.facade.response.TokenPayOpenByOrderIdResponse;
import cc.rengu.igas.channel.upac.facade.result.Result;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.common.enums.RespCodeEnum;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.model.UserInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.UserService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.igas.share.core.realize.impl.UserServiceImpl;
import cc.rengu.igas.share.core.service.base.NoticeService;
import cc.rengu.igas.share.facade.request.UpacPayResultNoticeRequest;
import cc.rengu.igas.share.facade.response.UpacPayResultNoticeResponse;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.DstChannelCfgMapper;
import cc.rengu.oltp.service.common.dao.SignAcctInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.DstChannelCfgMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SignAcctInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.TransCustomImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 银联全渠道支付结果通知服务
 * Created by fyp on 2020/5/6.
 */
public class UpacPayResultNoticeService extends NoticeService implements TransCustomImpl {

    @Override
    protected Object bizBeforeCust() throws Exception {
        UpacPayResultNoticeRequest upacPayResultNoticeRequest = new UpacPayResultNoticeRequest();
        ConvertUtil.convertOutput(upacPayResultNoticeRequest);
        return upacPayResultNoticeRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        UpacPayResultNoticeRequest upacPayResultNoticeRequest = (UpacPayResultNoticeRequest) request;
        BizResponse bizResponse = new BizResponse();
        UpacPayResultNoticeResponse payResultNoticeResponse = new UpacPayResultNoticeResponse();
        payResultNoticeResponse.setHeader(upacPayResultNoticeRequest.getHeader());
        String instId = upacPayResultNoticeRequest.getHeader().getInstId();
        String orderId = upacPayResultNoticeRequest.getOrderId();

        /* 根据订单号查询订单信息 */
        OrderService orderService = new OrderServiceImpl();
        OrderInfo orderInfo = orderService.selectOrderInfoBySysSeqNum(instId, orderId);
        if (null == orderInfo) {
            rglog.error("机构<{}>没有对应的银联订单号<{}>信息", upacPayResultNoticeRequest.getHeader().getInstId(), upacPayResultNoticeRequest.getOrderId());
            throw new BizException(RespCodeEnum.ORDER_NOT_EXIST.getRespCode(), RespCodeEnum.ORDER_NOT_EXIST.getRespDesc());
        }
        UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
        List<MchntOrderInfo> mchntOrderInfoList = orderInfo.getMchntOrderInfoList();
        Optional<PayOrderInfo> payOrderInfoOpt = orderInfo.getPayOrderInfoList().stream().filter(item -> item.getMsgDstId().equals(ChannelEnum.UPAC.getChannelType())).findFirst();
        if (!payOrderInfoOpt.isPresent()) {
            rglog.error("机构<{}>没有对应的银联订单号<{}>信息", upacPayResultNoticeRequest.getHeader().getInstId(), upacPayResultNoticeRequest.getOrderId());
            throw new BizException(RespCodeEnum.ORDER_NOT_EXIST.getRespCode(), RespCodeEnum.ORDER_NOT_EXIST.getRespDesc());
        }
        PayOrderInfo payOrderInfo = payOrderInfoOpt.get();
        if (TransStatusEnum.TRANS_SUCC.getStatus().equals(payOrderInfo.getTransStatus()) &&
                (BizStatusEnum.FINISH.getStatus().equals(payOrderInfo.getBizStatus()) ||
                        BizStatusEnum.REFUND.getStatus().equals(payOrderInfo.getBizStatus()) ||
                        BizStatusEnum.PART_REFUND.getStatus().equals(payOrderInfo.getBizStatus()) ||
                        BizStatusEnum.CONFIRM.getStatus().equals(payOrderInfo.getBizStatus()))) {
            rglog.error("订单已成功，不处理直接返回结果");
            payResultNoticeResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            payResultNoticeResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            bizResponse.setResult(payResultNoticeResponse);
            bizResponse.setRspSysId(AppParamConstant.IGAS);
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            return bizResponse;
        }

        /* 根据响应结果修改交易状态 */
        String respCode = upacPayResultNoticeRequest.getRespCode();
        rglog.info("无跳转通知中原交易的应答码:<{}>", respCode);
        if (!"00".equals(respCode)) {
            /*更新订单表状态为失败*/
            userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                mchntOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                mchntOrderInfo.setRealSettleAmt(AmountUtil.subtraction(mchntOrderInfo.getRealSettleAmt(), mchntOrderInfo.getCustomerMarketAmt()));
                mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            }
            payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
        } else {
            /*支付成功,更新当前支付订单状态*/
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            }
            payOrderInfo.setChannelSeqNum(upacPayResultNoticeRequest.getChannelSeqNum());
            payOrderInfo.setSettleDate(upacPayResultNoticeRequest.getSettleDate());
            payOrderInfo.setRespCode(upacPayResultNoticeRequest.getRespCode());
            payOrderInfo.setRespDesc(upacPayResultNoticeRequest.getRespDesc());
            payOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        }
        payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        GlobalTransUtil.setCacheValue(TransCacheConstant.MCHNT_ORDER_INFO_LIST, mchntOrderInfoList);

        /* 更新订单信息 */
        if (!orderService.updateOrderInfo(userOrderInfo, mchntOrderInfoList, payOrderInfo)) {
            rglog.error("更新支付订单状态失败");
            throw new BizException(RespCodeEnum.ORDER_UPDATE_ERROR.getRespCode(), RespCodeEnum.ORDER_UPDATE_ERROR.getRespDesc());
        }

        //调用通道接口
        if (null == txnInfo.getChannelCallCfgList() || txnInfo.getChannelCallCfgList().isEmpty()) {
            rglog.error("<{}-{}>交易未配置交易通道服务调用配置信息！", txnInfo.getSrcTxnAuthCfg().getTxnNum(), txnInfo.getSrcTxnAuthCfg().getTxnName());
            throw new BizException(RespCodeEnum.TRANS_NOT_SUPPORT.getRespCode(), RespCodeEnum.TRANS_NOT_SUPPORT.getRespDesc());
        }
        List<ChannelCallCfg> channelCallCfgList = txnInfo.getChannelCallCfgList().stream().filter(item ->
                item.getCallIndex().equals(ChannelBaseService.FIRST_CHANNEL_CALL_INDEX)).collect(Collectors.toList());
        ChannelCallCfg channelCallCfg = channelCallSceneDiscern(upacPayResultNoticeRequest, channelCallCfgList);
        Class channelClasz = Class.forName(channelCallCfg.getCallChannelImpl());
        ChannelBaseService channelBaseService = (ChannelBaseService) channelClasz.newInstance();
        channelBaseService.callService(txnInfo, orderInfo, channelCallCfg.getBizScene(), request);

        /* 组装应答报文 */
        bizResponse.setResult(payResultNoticeResponse);
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        if (!"00".equals(respCode)) {
            bizResponse.setRespDesc(RespCodeEnum.TRANS_IN_PROGRESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_IN_PROGRESS.getRespDesc());
        } else {
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            /* 更新商户累计限额 */
            MchntService mchntService = new MchntServiceImpl();
            mchntService.updateMchntTransLimit(mchntOrderInfoList);
        }
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        UpacPayResultNoticeResponse payResultNoticeResponse = (UpacPayResultNoticeResponse) bizResponse.getResult();
        ConvertUtil.convertInput(payResultNoticeResponse);
    }

    /**
     * 生成收银台用户信息
     *
     * @param upacPayResultNoticeRequest    请求对象
     * @param tokenPayOpenByOrderIdResponse 银联全渠道申请TOKEN应答信息
     * @param signAcctInfo                  签约信息
     * @param acqReservedJson               银联全渠道预留信息
     * @return 收银台用户信息
     * @throws Exception 异常
     */
    private UserInfo generateUserInfo(UpacPayResultNoticeRequest upacPayResultNoticeRequest, TokenPayOpenByOrderIdResponse tokenPayOpenByOrderIdResponse, SignAcctInfo signAcctInfo, JSONObject acqReservedJson) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = upacPayResultNoticeRequest.getHeader().getInstId();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        String sequenceNo = sysSeqNum.substring(sysSeqNum.length() - 8);
        String userInst = acqReservedJson.getString("userInst");
        String userId = acqReservedJson.getString("userId");
        UserInfo userInfo = new UserInfo();
        userInfo.setInstId(upacPayResultNoticeRequest.getHeader().getInstId());
        userInfo.setUserInst(userInst);
        if (StringUtil.isEmptyOrNull(userId)) {
            userInfo.setUserId(instId + DateUtil.getCurrentDate() + sequenceNo);
        } else {
            userInfo.setUserId(userId);
        }
        //用户加密盐生成规则：当前机构号+8位日期+8为序列号
        userInfo.setTransPasswordSalt(instId + DateUtil.getCurrentDate() + sequenceNo);
        CustomerInfo customerInfo = tokenPayOpenByOrderIdResponse.getCustomerInfo();
        userInfo.setUserName(StringUtil.isEmptyOrNull(customerInfo.getCustName()) ? signAcctInfo.getCardHoldName() : customerInfo.getCustName());
        userInfo.setMobileNo(customerInfo.getPhoneNo());
        userInfo.setCertType(StringUtil.isEmptyOrNull(customerInfo.getCertType()) ? signAcctInfo.getCertType() : customerInfo.getCertType());
        userInfo.setCertNo(StringUtil.isEmptyOrNull(customerInfo.getCertNo()) ? signAcctInfo.getCertNo() : customerInfo.getCertNo());
        userInfo.setUserStatus("00");
        userInfo.setTransPasswordErrorTimes(0);
        return userInfo;
    }


    /**
     * 更新签约信息表
     *
     * @param signAcctInfo                  签约实体
     * @param tokenPayOpenByOrderIdResponse 银联全渠道申请TOKEN响应实体
     */
    private void updateSignInfo(SignAcctInfo signAcctInfo, TokenPayOpenByOrderIdResponse tokenPayOpenByOrderIdResponse) {
        CustomerInfo customerInfo = tokenPayOpenByOrderIdResponse.getCustomerInfo();
        TokenPayInfo tokenPayInfo = tokenPayOpenByOrderIdResponse.getTokenPayInfo();
        String branchNo = signAcctInfo.getSignToken().split("\\|")[0];
        signAcctInfo.setSignToken(branchNo + "|" + tokenPayInfo.getToken());
        signAcctInfo.setReserveMobileNo(customerInfo.getPhoneNo());
        signAcctInfo.setSignExpiryDate(tokenPayInfo.getTokenEnd().substring(0, 8));
        signAcctInfo.setSignStatus(AppParamConstant.YES);
    }

    /**
     * 获取银联全渠道商户信息
     *
     * @param instId  多法人标识
     * @param mchntNo 商户号
     * @return 银联全渠道商户相关信息
     * @throws Exception 异常
     */
    private JSONObject getUpacMchntInfo(String instId, String mchntNo) throws Exception {
        //从支付通道信息表获取全渠道的 tokenId 和 tokenType
        DstChannelCfgMapper dstChannelCfgMapper = new DstChannelCfgMapperImpl();
        List<DstChannelCfg> dstChannelCfgList = dstChannelCfgMapper.selectDstChannelCfgBydstChannelId(instId, ChannelEnum.UPAC.getChannelType());
        if (null == dstChannelCfgList || dstChannelCfgList.isEmpty()) {
            rglog.error("银联全渠道通道配置(T_P_DST_CHANNEL_CFG)不存在!");
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        Optional<DstChannelCfg> dstChannelCfgOpt = dstChannelCfgList.stream().filter(item -> item.getDstChannelType().startsWith("TK")).min(Comparator.comparing(DstChannelCfg::getDstChannelType));
        if (!dstChannelCfgOpt.isPresent() || StringUtil.isEmptyOrNull(dstChannelCfgOpt.get().getOtherConfParam())) {
            rglog.error("银联全渠道不存在可用的tokenType和tokenId！");
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        JSONObject jsonObject = JSONObject.parseObject(dstChannelCfgOpt.get().getOtherConfParam());
        String trId = jsonObject.getString("trId");
        String tokenType = jsonObject.getString("tokenType");
        if (null == trId || null == tokenType) {
            rglog.error("银联全渠道不存在可用的tokenType和tokenId！");
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        String prodType = dstChannelCfgOpt.get().getDstChannelType();
        String upacMchntNo = dstChannelCfgOpt.get().getProviderMchntNo();
        if (null == upacMchntNo || StringUtil.isEmptyOrNull(prodType)) {
            rglog.error("商户未开通银联业务，不支持银联token支付");
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        //获取商户的银联全渠道商户信息
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(instId, mchntNo);
        if (null != mchntInfo) {
            Map<String, Object> mchntMap = JSONObject.parseObject(mchntInfo.getCupsChannelMchntNo());
            for (Map.Entry entry : mchntMap.entrySet()) {
                if (((String) entry.getKey()).startsWith("TK")) {
                    prodType = (String) entry.getKey();
                    upacMchntNo = (String) entry.getValue();
                    break;
                }
            }
            /*存储子商户号和子商户名称*/
            String accessType = jsonObject.getString("accessType");
            if (!StringUtil.isEmptyOrNull(accessType) && "2".equals(accessType)) {
                rglog.info("平台商户接入模式，保存子商户号和商户名称");
                jsonObject.put("subMerId", mchntInfo.getMchntNo());
                jsonObject.put("subMerName", mchntInfo.getMchntName());
            }
        }
        jsonObject.put("prodType", prodType);
        jsonObject.put("merId", upacMchntNo);
        return jsonObject;
    }

    @Override
    public ChannelCallCfg channelCallSceneDiscern(Object request, List<ChannelCallCfg> channelCallCfgList) throws Exception {
        /* 业务场景类型：00-原支付失败场景，01-原支付交易成功 */
        UpacPayResultNoticeRequest upacPayResultNoticeRequest = (UpacPayResultNoticeRequest) request;
        if (!RespCodeEnum.TRANS_SUCCESS.getRespCode().equals(upacPayResultNoticeRequest.getRespCode())) {
            /* 原支付交易失败 */
            Optional<ChannelCallCfg> channelCallCfgOpt = channelCallCfgList.stream().filter(item -> item.getBizScene().equals("00")).findFirst();
            return channelCallCfgOpt.orElse(null);
        } else {
            /* 原支付交易成功 */
            if ("0101".equals(channelCallCfgList.get(0).getCallIndex())) {
                List<MchntOrderInfo> mchntOrderInfoList = (List<MchntOrderInfo>) GlobalTransUtil.getCacheValue(TransCacheConstant.MCHNT_ORDER_INFO_LIST);
                if (null != mchntOrderInfoList && !"00".equals(mchntOrderInfoList.get(0).getBizSceneType()) &&
                        !"01".equals(mchntOrderInfoList.get(0).getBizSceneType()) && !"02".equals(mchntOrderInfoList.get(0).getBizSceneType())) {
                    if (AppParamConstant.YES.equals(mchntOrderInfoList.get(0).getRealSettleFlag())) {
                        /* 商户实时入账场景：调用核心进行商户实时入账 */
                        Optional<ChannelCallCfg> channelCallCfgOpt = channelCallCfgList.stream().filter(item -> item.getCallChannelId().equals(ChannelEnum.ESB.getChannelType())).findFirst();
                        return channelCallCfgOpt.orElse(null);
                    } else if (!"0".equals(mchntOrderInfoList.get(0).getFeeInputMode())) {
                        /* 非特殊计费场景：调用虚拟账户平台记商户虚拟账户余额 */
                        Optional<ChannelCallCfg> channelCallCfgOpt = channelCallCfgList.stream().filter(item -> item.getCallChannelId().equals(ChannelEnum.ACCT.getChannelType())).findFirst();
                        return channelCallCfgOpt.orElse(null);
                    } else {
                        /* 特殊计费场景：交易结果通知 */
                        Optional<ChannelCallCfg> channelCallCfgOpt = channelCallCfgList.stream().filter(item -> item.getCallChannelId().equals("LOCAL")).findFirst();
                        return channelCallCfgOpt.orElse(null);
                    }
                }
            }
        }
        return null;
    }

    @Override
    public CheckResultEnum channelCallPreCheck(Object request, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        UpacPayResultNoticeRequest upacPayResultNoticeRequest = (UpacPayResultNoticeRequest) request;
        String instId = upacPayResultNoticeRequest.getHeader().getInstId();
        String mchntNo = orderInfo.getMchntOrderInfoList().get(0).getMchntNo();
        if (ChannelEnum.UPAC.getChannelType().equals(channelCallCfg.getCallChannelId())) {
            /* 若为签约并支付则更新签约用户及银行卡签约信息 */
            String acqReserved = upacPayResultNoticeRequest.getAcqReserved();
            JSONObject acqReservedJson = JSONObject.parseObject(new String(Base64.decodeBase64(acqReserved)), JSONObject.class);
            rglog.info("无跳转保留域中的数据:<{}>", acqReservedJson);
            String signTransType = acqReservedJson.getString("transType");
            if (!StringUtil.isEmptyOrNull(signTransType)) {
                /* 申请银联全渠道签约TOKEN信息:平台级签约需要上送subMerName、subMerId、subMerAbbr */
                JSONObject jsonObject = getUpacMchntInfo(instId, mchntNo);
                String accessType = jsonObject.getString("accessType");
                xmlTreeUtil.setXmlTreeStringValue("accessType", StringUtil.isEmptyOrNull(accessType) ? "0" : accessType);
                if ("2".equals(accessType)) {
                    /*平台模式上送二级商户信息*/
                    xmlTreeUtil.setXmlTreeStringValue("subMerId", jsonObject.getString("subMerId"));
                    xmlTreeUtil.setXmlTreeStringValue("subMerName", jsonObject.getString("subMerName"));
                    xmlTreeUtil.setXmlTreeStringValue("subMerAbbr", jsonObject.getString("subMerAbbr"));
                }
                xmlTreeUtil.setXmlTreeStringValue("upacMchntNo", upacPayResultNoticeRequest.getUpacMchntNo());
                xmlTreeUtil.setXmlTreeStringValue("orderId", upacPayResultNoticeRequest.getOrderId());
                xmlTreeUtil.setXmlTreeStringValue("orderTime", upacPayResultNoticeRequest.getOrderTime());
                xmlTreeUtil.setXmlTreeStringValue("prodType", jsonObject.getString("prodType"));
                return CheckResultEnum.PASSED;
            } else {
                return CheckResultEnum.NEXT;
            }
        } else {
            return CheckResultEnum.PASSED;
        }
    }

    @Override
    public TransStatusEnum channelCallResultProc(Object request, ChannelCallCfg channelCallCfg, TransStatusEnum transStatusEnum, Object channelResponse, OrderInfo needUpdateOrderInfo) throws Exception {
        UpacPayResultNoticeRequest upacPayResultNoticeRequest = (UpacPayResultNoticeRequest) request;
        String instId = upacPayResultNoticeRequest.getHeader().getInstId();
        String orderId = upacPayResultNoticeRequest.getOrderId();
        if (TransStatusEnum.TRANS_SUCC.equals(transStatusEnum) && null != channelResponse) {
            if (ChannelEnum.UPAC.getChannelType().equals(channelCallCfg.getCallChannelId())) {
                Result<TokenPayOpenByOrderIdResponse> callResult = (Result<TokenPayOpenByOrderIdResponse>) channelResponse;
                TokenPayOpenByOrderIdResponse tokenPayOpenByOrderIdResponse = callResult.getResult();
                /* 首首签约并支付场景，需要登记用户及更新签约信息 */
                SignAcctInfoMapper signAcctInfoMapper = new SignAcctInfoMapperImpl();
                SignAcctInfo signAcctInfo = signAcctInfoMapper.selectSignAcctInfoBySignSeqNum(instId, orderId);
                if (null == signAcctInfo) {
                    rglog.info("原全渠道签约申请交易不存在");
                    throw new BizException(RespCodeEnum.SIGN_INFO_NOT_EXIST.getRespCode(), RespCodeEnum.SIGN_INFO_NOT_EXIST.getRespDesc());
                }
                /* 获取银联全渠道预留信息 */
                String acqReserved = upacPayResultNoticeRequest.getAcqReserved();
                JSONObject acqReservedJson = JSONObject.parseObject(new String(Base64.decodeBase64(acqReserved)), JSONObject.class);
                rglog.info("无跳转保留域中的数据:<{}>", acqReservedJson);
                String signTransType = acqReservedJson.getString("transType");
                /* 更新签约用户及签约信息 */
                UserService userService = new UserServiceImpl();
                if ("0".equals(signTransType)) {
                    /*首次签约并支付登记用户信息 */
                    UserInfo userInfo = generateUserInfo(upacPayResultNoticeRequest, tokenPayOpenByOrderIdResponse, signAcctInfo, acqReservedJson);
                    boolean registerFlag = userService.registerUserInfo(userInfo);
                    if (!registerFlag) {
                        throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                    }
                }
                updateSignInfo(signAcctInfo, tokenPayOpenByOrderIdResponse);
                int iReturnCode = signAcctInfoMapper.updateSignAcctInfoBySignAcctNo(signAcctInfo);
                if (0 != iReturnCode) {
                    rglog.error("更新签约信息表失败,signAcctInfo:<{}>", JSONObject.toJSONString(signAcctInfo));
                }
            }
        }
        return transStatusEnum;
    }
}
